package com.bdhub.handld;

import com.bdhub.TimeoutTimer;
import com.bdhub.common.MessageType;
import com.bdhub.im.server.protobuf.MessageProtobuf.CMsg;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 消息发送超时管理
 * 
 * @author lp
 * 
 */
public class MessageTimeOutManager {
	private static final Map<String, TimeoutTimer> msgMap = new ConcurrentHashMap<String, TimeoutTimer>();
    private ClientBootstrap clientBootstrap;
	public  MessageTimeOutManager(ClientBootstrap clientBootstrap) {
		this.clientBootstrap = clientBootstrap;
	}
	public void clear() {
		Iterator<Entry<String, TimeoutTimer>> its = msgMap.entrySet()
				.iterator();
		while (its.hasNext()) {
			its.next().getValue().cancel();
			its.remove();
		}
	}

	/**
	 * 添加定时器
	 * 
	 * @param message
	 */
	public void add(CMsg message) {
		String mid = message.getHead().getMid();
		if (!msgMap.containsKey(mid)) {
			TimeoutTimer timer = new TimeoutTimer(clientBootstrap,message);
			msgMap.put(mid, timer);
		}
	}

	/**
	 * 删除定时器
	 * 
	 * @param mid
	 */
	public void removeAndStop(String mid) {
		TimeoutTimer ter = remove(mid);
		if (null != ter) {
			ter.cancel();
			ter = null;
		}
	}

	public TimeoutTimer remove(String mid) {
		return msgMap.remove(mid);
	}

	/**
	 * 重连成功通知(IMS登录成功事件)
	 */
	public synchronized void connectReset() {
		Entry<String, TimeoutTimer> entry;
		for (Iterator<Entry<String, TimeoutTimer>> it = msgMap.entrySet()
				.iterator(); it.hasNext();) {
			entry = it.next();
			// 移除登录的消息
			if (entry.getValue().getMessage().getHead().getType() == MessageType.LOGIN_REQ
					.value()) {
				it.remove();
			} else {
				// 重新发送对列里剩余的消息
				entry.getValue().sendMessage();
			}
		}

	}

}
